package com.zhp.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {

    protected String getUserId(HttpServletRequest req){
        //获取当前登录的用户Id
       return req.getSession().getAttribute(req.getSession().getId()).toString();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        boolean contains = url.contains("?");
        String name = null;
        if (contains){
            name =url.substring(url.lastIndexOf("/") + 1,url.indexOf("?"));
        }else {
            name =url.substring(url.lastIndexOf("/") + 1);
        }
        Class<? extends BaseController> aClass = this.getClass();
        Method method = null;
        try {
            method = aClass.getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(aClass.newInstance(),req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
